package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Appointment;
import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IAppointmentService;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.ibatis.builder.BuilderException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private IServiceItemService serviceItemService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;




    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        /*List<CarPackageAudit> carPackageAudits = carPackageAuditMapper.selectForList(qo);
        for (CarPackageAudit carPackageAudit : carPackageAudits) {
            carPackageAudit.setServiceItem(serviceItemService.get(carPackageAudit.getServiceItemId()));
        }*/
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {

        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {

        //选择第二个
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);

    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public void updateInstanceId(Long id, String instanceId) {
        carPackageAuditMapper.updateInstanceId(id, instanceId);
    }

    @Override
    public InputStream processImg(Long id) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        InputStream inputStream = null;
        //更加流程文件使用代码方式画出来
        BpmnInfo bpmnInfo = bpmnInfoService.get(carPackageAudit.getBpmnInfoId());
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());

        ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        if(CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            //审核中
            Task task = taskService.createTaskQuery()
                    .processInstanceId(carPackageAudit.getInstanceId()).singleResult();

            List<String> activeActivityIds =
                    runtimeService.getActiveActivityIds(task.getExecutionId());

            inputStream = generator.generateDiagram(model, activeActivityIds,
                    Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
        }else{
            //结束
            inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
        }


        return inputStream;
    }

    @Override
    public void cancelApply(Long id) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //满足撤销条件
        if(carPackageAudit == null || !CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            throw new BusinessException("必须是在审核中状态才允许撤销");
        }
        //套餐服务修改状态--初始化
        serviceItemService.changeAuditStatus(carPackageAudit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);

        //套餐审核记录状态-撤销
        carPackageAuditMapper.changeStatus(id,CarPackageAudit.STATUS_CANCEL);

        //审核流程实例被删除
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(), "审核流程撤销");
    }

    //操作前确定可能需要变动数据： ServiceItem CarPackageAudit
    @Override
    public void audit(Long id, int auditStatus, String info) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //1:判断审核条件
        //1>carPackageAudit 必须存在
        //2>carPackageAudit 状态必须是审核中
        if(carPackageAudit == null || !CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            throw new BusinessException("只有在审核中状态的数据才允许审核");
        }
        //CarPackageAudit 设置审核备注
        String temp = carPackageAudit.getAuditRecord() + "<br>";
        if(auditStatus == 2){
            temp += "【"+ ShiroUtils.getLoginName() +" 同意】,备注：" + info;
        }else{
            temp += "【"+ ShiroUtils.getLoginName() +" 拒绝】,备注：" + info;
        }
        carPackageAudit.setAuditRecord(temp); //@TODO
        //CarPackageAudit 设置审核时间
        carPackageAudit.setAuditTime(new Date());

        //执行一次任务， 让流程跑到下一个节点
        Task task = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();

        //设置审核流程分支中审核状态： auditStatus
        taskService.setVariable(task.getId(), "auditStatus",auditStatus);
        //流程审核备注--activiti7
        taskService.addComment(task.getId(), carPackageAudit.getInstanceId(), temp);
        taskService.complete(task.getId());

        if(auditStatus == CarPackageAudit.STATUS_PASS){
            //2:审核通过
            // 2.1: 判断流程是否结束(判断是否有下一个节点-Task)
            Task nextTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();

            if(nextTask == null){
                // 2.2: 如果没有下一个节点
                //      1>ServiceItem 状态变成审核通过
                serviceItemService.changeAuditStatus(carPackageAudit.getServiceItemId(), ServiceItem.AUDITSTATUS_APPROVED);
                //      2>CarPackageAudit 状态变成审核通过
                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
            }else{
                // 2.3: 如果有下一个节点
                //      1>CarPackageAudit 设置下一个审核人
                String assignee = nextTask.getAssignee();
                carPackageAudit.setAuditorId(Long.parseLong(assignee));
            }
        }else{
            //3:审核拒绝
            //1>ServiceItem 状态变成初始化
            serviceItemService.changeAuditStatus(carPackageAudit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
            //2>CarPackageAudit 状态变成 审核拒绝
            carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);
        }
        //最后更新
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }
}
